package com.tod.shiro.shirodemo.day01;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;

/**
 * 创建自己的认证领域
 * 需要将自定义的领域类配置到shiro-realm.ini中
 *
 * @author Tod.xie
 */
public class MyRealm implements Realm {
    @Override
    public String getName() {
        return "TodRealm";
    }

    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        //仅支持UsernamePasswordToken类型的authenticationToken
        return authenticationToken instanceof UsernamePasswordToken;
    }

    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名
        String username = (String)authenticationToken.getPrincipal();
        //得到密码
        String password = new String((char[])authenticationToken.getCredentials());
        if(!"Tod.xie".equals(username)) {
            //如果用户名错误
            throw new UnknownAccountException();
        }
        if(!"123".equals(password)) {
            //如果密码错误
            throw new IncorrectCredentialsException();
        }
        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
